﻿using ExcelDataReader;
using Heroius.Extension;
using Heroius.Extension.WPF;
using Microsoft.Win32;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Diagnostics;
using Heroius.Extension.Desktop.Utility;
using Heroius.Extension.Desktop;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;

namespace Heroius.NeuTabDiff
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();

            TbVer.Text = $"Ver: {Assembly.GetExecutingAssembly().GetName().Version.ToString(4)}, Powered by Heroius-Extension, 专属定制：东北大学教务处";

            var logpath = $"{Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)}\\Heroius\\NeuTabDiff\\logs\\{DateTime.Now:yyyyMMdd}.log";
            PathHelper.CreateDirectory(logpath);
            Logger = new TextLogger(logpath);

            OpenDia = new OpenFileDialog()
            {
                Filter = "Excel文件|*.xlsx|Excel文件（旧格式）|*.xls"
            };

            ExBar.AddButton("打开基础表", "/Heroius.NeuTabDiff;Component/img/bopen.png", this, "OpenBasicTab");
            ExBar.AddButton("打开学院表", "/Heroius.NeuTabDiff;Component/img/copen.png", this, "OpenCollegeTab");
            ExBar.AddButton("执行记录识别", "/Heroius.NeuTabDiff;Component/img/play.png", this, "ExcuteDiff");
            ExBar.AddButton("帮助", "/Heroius.NeuTabDiff;Component/img/help.png", this, "Help");

            BasicRecords = new RecordCollection();
            CollegeRecords = new RecordCollection();
            LackRecords = new RecordCollection();
            OverRecords = new RecordCollection();
            DupRecords = new RecordCollection();

            DataContext = this;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public ObservableCollection<ExToolBar.IconButtonInfo> ExButtons { get; set; }
        public RecordCollection BasicRecords { get; set; }
        public RecordCollection CollegeRecords { get; set; }
        public RecordCollection LackRecords { get; set; }
        public RecordCollection OverRecords { get; set; }
        public RecordCollection DupRecords { get; set; }
        public OpenFileDialog OpenDia;
        public TextLogger Logger;

        public bool Loaded_Basic = false, Loaded_College = false;

        public void OpenBasicTab()
        {
            OpenTabTo(BasicRecords, DgBasic, TcBasic, ref Loaded_Basic);
        }

        public void OpenCollegeTab()
        {
            OpenTabTo(CollegeRecords, DgCollege, TcCollege, ref Loaded_College);
        }

        void OpenTabTo(RecordCollection target, DataGrid dg, TextBlock tb, ref bool mark)
        {
            try
            {
                if (OpenDia.ShowDialog() == true)
                {
#if DEBUG

                    DateTime __d1, __d2;
#endif
                    mark = false;
                    using (Stream stream = OpenDia.OpenFile())
                    {
                        var reader = ExcelReaderFactory.CreateReader(stream);
#if DEBUG
                        Logger.Write($"EDR recs cnt:{reader.RowCount}");
                        __d1 = DateTime.Now;
#endif
                        if (reader.Read())
                        {
                            int fieldc = reader.FieldCount;
                            List<string> header = new List<string>();
                            int ki = -1, gi = -1;
                            for (int i = 0; i < fieldc; i++)
                            {
                                string cv = reader.GetString(i);
                                if (string.IsNullOrWhiteSpace(cv))
                                {
                                    fieldc = i;
                                    break;
                                }
                                else
                                {
                                    header.Add(cv);
                                    if (cv == "开课号") ki = i;
                                    if (cv == "开课单位") gi = i;
                                }
                            }

                            target.DefineExtProps(ki, gi, header.ToArray());

                            while (reader.Read())
                            {
                                if (reader.GetValue(0) == null)
                                    break;
                                string[] cells = new string[fieldc];

                                for (int i = 0; i < fieldc; i++)
                                {
                                    cells[i] = reader.GetValue(i).As("");
                                }
                                target.Add(cells);
                            }
                        }
#if DEBUG
                        __d2 = DateTime.Now;
                        Logger.Write($"EDR read during: {(__d2 - __d1).TotalMilliseconds} ms");
#endif
                        reader.Close();
                    }
                    target.UpdateDg(dg, tb);
                    mark = true;
#if DEBUG
                    Logger.Write($"DataGrid during: {(DateTime.Now - __d2).TotalMilliseconds} ms");
#endif

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Logger.Write($"Err on Open:{ex.Message}");
            }
        }

        public void ExcuteDiff() {
            try
            {
                if (Loaded_Basic && Loaded_College)
                {
                    LackRecords.DefineExtProps(BasicRecords);
                    OverRecords.DefineExtProps(CollegeRecords);
                    DupRecords.DefineExtProps(CollegeRecords);

                    var bf = BasicRecords.PropValues.Where(v => v.GroupValue == CollegeRecords.PropValues[0].GroupValue);
                    var cmp = new RecordComparer();
                    LackRecords.PropValues.AddRange(bf.Except(CollegeRecords.PropValues, cmp));
                    OverRecords.PropValues.AddRange(CollegeRecords.PropValues.Except(bf, cmp));
                    DupRecords.PropValues.AddRange(CollegeRecords.PropValues.Except(CollegeRecords.PropValues.Distinct(cmp)));

                    LackRecords.UpdateDg(DgLack, TcLack);
                    OverRecords.UpdateDg(DgOver, TcOver);
                    DupRecords.UpdateDg(DgDup, TcDup);
                }
                else
                {
                    MessageBox.Show("无法执行，数据尚未有效加载！");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Logger.Write($"Err on Exec:{ex.Message}");
            }
        }
        public void Help() {
            try
            {
                Process.Start("https://gitee.com/heroius/heroius.-neu-tab-diff/wikis/Home");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Logger.Write($"Err on Help:{ex.Message}");
            }
        }

    }
}
